package com.yc.navy.dayfresh.controller;

import com.yc.navy.dayfresh.biz.BizException;
import com.yc.navy.dayfresh.biz.FavBiz;
import com.yc.navy.dayfresh.dto.Result;
import com.yc.navy.dayfresh.entity.Fav;
import com.yc.navy.dayfresh.entity.User;
import com.yc.navy.dayfresh.mapper.FavMapper;
import com.yc.starter.login.config.LoginProperties;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/9
 * @email haijunzhou@hnit.edu.cn
 */
@RestController
@RequestMapping("fav")
public class FavController {

    @Autowired
    FavMapper favMapper;

    @RequestMapping("queryAll")
    List<Fav> queryAll(){
        return favMapper.selectList(null);
    }

    @Autowired
    FavBiz favBiz;

    @Autowired
    LoginProperties loginProperties;
    @RequestMapping("create")
    Result create(@RequestBody Fav fav
            , HttpSession session
                  ){
        // 设置用户id
        User user = (User) session.getAttribute(loginProperties.getSessionKey());
        fav.setUid(user.getId());
        try {
            favBiz.add(fav);
            return new Result(1,"链接收藏成功!",fav);
        } catch (BizException e) {
            return new Result(e.getCode(),e.getMessage(),null);
        }
    }

    @RequestMapping("toTop")
    Result toTop(@RequestBody Fav fav){
        favBiz.toTop(fav);
        return new Result(1,"置顶成功!",fav);
    }

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("openLink")
    Result openLink(int fid){
        System.out.println("-------------openLink-------------" + fid);
        HashOperations hash = redisTemplate.opsForHash();
        Integer favOpens = (Integer) hash.get("fav_opens", fid);
        //hash.increment("fav_opens", fid, 1);
        hash.put("fav_opens", fid, ++favOpens);
        return new Result(1,"浏览量+1",null);
    }

    @Scheduled(cron="0 0 0/1 * * *") // 设置为1小时执行一次
    @Transactional
    public void updateOpens(){
        System.out.println("-------------updateOpens-------------");
        HashOperations hash = redisTemplate.opsForHash();
        Map map = hash.entries("fav_opens");
        Fav fav = new Fav();
        map.forEach((fid,opens)->{
            fav.setId((Integer) fid);
            fav.setOpens((Integer) opens);
            favMapper.updateById(fav);
        });
    }

    @RequestMapping("getInfo")
    public Fav getInfo(String addr) throws IOException {
        if(addr == null || addr.isBlank()){
            return null;
        }
        Fav fav = new Fav();
        if(addr.startsWith("http") == false){
            addr = "http://" + addr;
            fav.setAddr(addr);
        }
        URL url = new URL(addr);
        Document doc = Jsoup.parse(url, 5000);
        Elements title = doc.select("head>title");
        // 标题
        fav.setName(title.get(0).text());
        Element tags = doc.select("head>meta[name='Keywords']").get(0);
        // 分类
        fav.setTags(tags.attr("content"));
        Element info = doc.select("head>meta[name='Description']").get(0);
        // 介绍
        fav.setIntro(info.attr("content"));
        Elements image = doc.select("head>link[rel^='apple-touch-icon']");
        if(image.size() > 0){
            // 图片
            fav.setImage(image.get(0).attr("href"));
        }
        return fav;
    }

    @RequestMapping("/delete")
    Result delete(@RequestBody Fav fav){
        favBiz.delete(fav);
        return new Result(1, "删除成功", fav);
    }

    @RequestMapping("toFind")
    Result toFind(String name,HttpSession session){
        User user=(User) session.getAttribute(loginProperties.getSessionKey());
        System.out.println(user.getId());
        List<Fav> favs = favBiz.toFind(user.getId(),name);
        return new Result(1,"查询成功",favs);
    }
}
